/**
 * title:学子商城注册接口，采用promise封装数据库和模块化开发
 * author :王占胜
 * method：post
 * Elink: /user
 * 
 */
const express = require('express')
// 数据库封装模块
const { sqlname, chaxun } = require('../mysql')
// 密码加密
const md5 = require("md5")

var router = express.Router()
router.post("/user", (req, res,next) => {
    // console.log(req.body);
    // 注册前查询
    let sql2 = "select uname from xz_user where uname = ?"
    chaxun(sql2, req.body.uname).then(restult => {
        // console.log(restult);
        if (restult.length !== 0) {
            res.send({
                "code": 202,
                "message": "该用户已经存在！"
            })
            next()
        } else {
            zhuruSql()
        }
    }).catch(err => {
        console.log(err);
        next(err)
    })
    // 注入数据库
    function zhuruSql() {
        let sql = "insert into xz_user set ?"
        let myid = req.body
        sqlname(sql, myid).then(resa => {
            res.send({
                "code": 200,
                "message": "注册成功！"
            })
        }).catch(err => {
            console.log(err);
            res.send({
                "code": 201,
                "message": "注册失败！"
            })
        })
    }
})
module.exports = router